#ifndef _ROT_HPP
#define _ROT_HPP

static TaskHandle_t rotOpH;
static rotary_encoder_t *encoder = NULL;
static int currentValue = 0;
static uint32_t pcntUnit = 0;

void rotInit();
void rotA();
void rotB();
void rotC();
void rotOp();

void rotInit() {
	rotary_encoder_config_t rotConfig = ROTARY_ENCODER_DEFAULT_CONFIG((rotary_encoder_dev_t) pcntUnit, CONFIG_PIN_ROT_CLK, CONFIG_PIN_ROT_DT);
	
	ESP_ERROR_CHECK(rotary_encoder_new_ec11(&rotConfig, &encoder));
	ESP_ERROR_CHECK(encoder->set_glitch_filter(encoder, 1));
	ESP_ERROR_CHECK(encoder->start(encoder));

	gpio_config_t pinRotC = {
		.intr_type = 0,
		.mode = GPIO_MODE_INPUT,
		.pin_bit_mask = (1ULL << CONFIG_PIN_ROT_SW),
		.pull_up_en = 1
	};
	gpio_config(&pinRotC);

	// 编码器操作
	xTaskCreatePinnedToCore(rotOp, "rotOp", 1024 * 2, NULL, 0, &rotOpH, 1);

	while(1) {
		int getValue = encoder -> get_counter_value(encoder);
		if(getValue != currentValue) {
			// 顺时针旋转
			if(getValue > currentValue) {
				// xEventGroupSetBits(eventGroup, EVENT_ROT_A);
				xTaskNotify(rotOpH, BIT0, eSetValueWithoutOverwrite);
			}
			// 逆时针旋转
			else if(getValue < currentValue) {
				// xEventGroupSetBits(eventGroup, EVENT_ROT_B);
				xTaskNotify(rotOpH, BIT1, eSetValueWithoutOverwrite);
			}
			currentValue = getValue;
		}
		// 旋转编码器按键按下
		if(gpio_get_level(CONFIG_PIN_ROT_SW) == 0) {
			vTaskDelay(pdMS_TO_TICKS(150));
			// xEventGroupSetBits(eventGroup, EVENT_ROT_C);
			xTaskNotify(rotOpH, BIT2, eSetValueWithoutOverwrite);
		}
        vTaskDelay(pdMS_TO_TICKS(100));
	}
	vTaskDelete(NULL);

}

void rotOp() {
	uint32_t bit;
	while(1) {
		// printf("rotOP do\n");
		xTaskNotifyWait(
			ULONG_MAX,
			ULONG_MAX,
			&bit,
			portMAX_DELAY
		);
		if((bit & BIT0) != 0) {
			rotA();
		}
		if((bit & BIT1) != 0) {
			rotB();
		}
		if((bit & BIT2) != 0) {
			rotC();
		}

		vTaskDelay(pdMS_TO_TICKS(100));
	}
	vTaskDelete(NULL);
}

void rotA() {
	if(strcmp(currentPage, "home") == 0) {
		pageHomeScroll(0, 0);
	}
	
}

void rotB() {
	if(strcmp(currentPage, "home") == 0) {
		pageHomeScroll(1, 0);
	}
}

void rotC() {
	printf("rot c\n");
	// pageHomeTestLabel();
	// BaseType_t bits;
	// recMsg msg = {
	// 	.fromUser = "BG7YXY",
	// 	.msg = "QCQCQ DE BG7YXY BG7YXY PSK",
	// 	.recTime = "22:45:06",
	// 	.self = false
	// };
	// // bits = xQueueSend(wsDataQ, &msg, 0);
	// xQueueSend(wsDataQ, &msg, 0);
	// // printf("done\n");

	// // pageTestEvent();
}


#endif